package com.ruoyi.service.impl;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.mapper.DemoMapper;
import com.ruoyi.service.DemoService;
import com.ruoyi.utils.ElongUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class DemoServiceImpl implements DemoService {

    @Autowired
    DemoMapper demoMapper;

    @Override
    public List<Map> getData() {
        return demoMapper.getData();
    }

    @Override
    public void synchronizationCity() {
        String city = ElongUtils.getCity(1, 1700);
        JSONObject jsonObject = JSONObject.parseObject(city);
        JSONArray jsonArray = jsonObject.getJSONObject("Result").getJSONArray("Citys");
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject jsonObject1 = jsonArray.getJSONObject(i);
            String ProvinceName = jsonObject1.getString("ProvinceName");
            if (ProvinceName != null && !"".equals(ProvinceName)) {
                String s = ProvinceName.split("\\|")[1];
                Map cityObjByName = demoMapper.getCityObjByName(s);
                if (cityObjByName != null) {
                    String parentId = cityObjByName.get("id").toString();
                    String id = jsonObject1.get("CityId").toString();
                    String CityName = jsonObject1.get("CityName").toString();
                    String[] split = CityName.split("\\|");
                    Map map = new HashMap();
                    map.put("id", id);
                    map.put("name", split[split.length - 1]);
                    map.put("parentId", parentId);
                    demoMapper.insertCity(map);
                }
            }
        }
    }

    @Override
    public List<JSONObject> getCity() {
        List<JSONObject> cityProvince = demoMapper.getCityProvince();
        for (int i = 0; i < cityProvince.size(); i++) {
            JSONObject jsonObject = cityProvince.get(i);
            String id = jsonObject.getString("value");
            List<JSONObject> cityLand = demoMapper.getCityLand(id);
            jsonObject.put("children",cityLand);
        }
        return cityProvince;
    }
}



